package me.jzn.core.utils;

import java.io.File;
import java.io.IOException;

import me.jzn.core.Core;
import me.jzn.core.enums.FileFmt;
import me.jzn.core.exceptions.ShouldNotRunHereException;

/**
 * 处理  这样的数据,参见RFC2397
 * 因为用到了base64Util,因此放在libjava和alib中
 */
public class Base64DataUtil {
    public static String toBase64Data(byte[] bytes, String mime) {
        String base64 = Base64Util.encode(bytes, true);
        return String.format("data:%s;base64,%s", mime, base64);
    }

    public static String toBase64Data(File file) {
        try {
            byte[] bytes = FileUtil.readAll(file);

            String suffix = FileUtil.getSuffix(file.getName());
            if (Core.isDebug() && suffix == null) {
                throw new ShouldNotRunHereException("img suffix is null:" + file.getPath());
            }
            FileFmt fmt = FileFmt.fromSuffix(suffix);
            return toBase64Data(bytes, fmt.getMime());
        } catch (IOException e) {
            throw new ShouldNotRunHereException("read img error!", e);
        }
    }

    public static String getMime(String data) {
        return data.substring(data.indexOf(":") + 1, data.indexOf(";"));
    }

    public static byte[] getData(String data) {
        data = data.substring(data.indexOf(",") + 1);
        return Base64Util.decode(data);
    }
}
